package com.example.it_com.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.it_com.common.Result;
import com.example.it_com.entity.*;
import com.example.it_com.service.ForumpostService;
import com.example.it_com.service.PostcommentService;
import com.example.it_com.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/post")
@Slf4j
public class PostController {
    @Autowired
    private UserService userService;
    @Autowired
    private PostcommentService postcommentService;
    @Autowired
    private ForumpostService forumpostService;


    //用户发帖子
    @PostMapping("/publishpost")
    public Result<String> publishpost(Integer userId, String pTitle, String pDescription,String pType) {
        log.info(userId.toString());
        log.info(pTitle);
        log.info(pDescription);
        log.info(pType);

        //获取用户
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserId, userId);
        User one = userService.getOne(queryWrapper);

        Forumpost forumpost = new Forumpost();
        forumpost.setUserId(userId);
        forumpost.setPTitle(pTitle);
        forumpost.setPDescription(pDescription);
        forumpost.setPType(pType);
        forumpost.setPCreated(LocalDateTime.now());
        forumpost.setPUpdated(LocalDateTime.now());


        // 发布帖子
        boolean save = forumpostService.save(forumpost);
        // 是否保存成功
        if (save) {
            return Result.success("", "帖子发布成功");
        } else {
            return Result.error("", "帖子发布失败");
        }
    }


    //用户发帖子评论
    @PostMapping("/publishpostcomment")
    public Result<String> publishpostcomment(Integer userId,Integer postId,String pcContent) {
        log.info(userId.toString());
        log.info(postId.toString());
        log.info(pcContent);

        Postcomment postcomment = new Postcomment();
        postcomment.setUserId(userId);
        postcomment.setPostId(postId);
        postcomment.setPcContent(pcContent);
        postcomment.setPcCreated(LocalDateTime.now());
        postcomment.setPcLikecount(0);

        //更新帖子更新时间
        LambdaUpdateWrapper<Forumpost> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Forumpost::getPostId, postId)
                .set(Forumpost::getPUpdated, LocalDateTime.now());
        forumpostService.update(updateWrapper);


        // 保存帖子评论
        boolean save = postcommentService.save(postcomment);
        // 是否保存成功
        if (save) {
            return Result.success("", "帖子评论发布成功");
        } else {
            return Result.error("", "帖子评论发布失败");
        }
    }

    //帖子点赞
    @PostMapping("/likepost")
    public Result<String> likepost(Integer userId,Integer postId) {
        log.info(userId.toString());
        log.info(postId.toString());

        //点赞数量+1
        LambdaUpdateWrapper<Forumpost> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Forumpost::getPostId, postId)
                .setSql("like_count = like_count + 1");
        forumpostService.update(updateWrapper);

        return Result.success("", "帖子点赞成功");
    }

    //帖子评论点赞
    @PostMapping("/likepostcomment")
    public Result<String> likepostcomment(Integer userId,Integer postId,Integer postcommentId) {
        log.info(userId.toString());
        log.info(postId.toString());
        log.info(postcommentId.toString());

        //点赞数量+1
        LambdaUpdateWrapper<Postcomment> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Postcomment::getPostId, postId)
                .eq(Postcomment::getCommentId, postcommentId)
                .setSql("pc_likecount = pc_likecount + 1");

        postcommentService.update(updateWrapper);

        return Result.success("", "帖子评论点赞成功");

    }

//    //查看所有帖子
//    @PostMapping("/getallpost")
//    public Result<List<Forumpost>> getallpost() {
//
//
//        LambdaQueryWrapper<Forumpost> postqueryWrapper = new LambdaQueryWrapper<>();
//        List<Forumpost> posts = forumpostService.list(postqueryWrapper);
//
//
//        return Result.success(posts, "返回成功");
//    }

    //查看所有帖子，并根据作者id返回头像
    @PostMapping("/getallpost")
    public Result<List<PostWithComments>> getallpost() {
        //查询所有帖子
        LambdaQueryWrapper<Forumpost> queryWrapper = new LambdaQueryWrapper<>();
        List<Forumpost> posts = forumpostService.list(queryWrapper);
        List<PostWithComments> postWithCommentsList = new ArrayList<>();

        //对于每一个帖子查询作者头像
        for (Forumpost post : posts) {
            LambdaQueryWrapper<User> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(User::getUserId, post.getUserId());
            User user = userService.getOne(queryWrapper1);

            // 检查 user 是否为 null
            if (user == null) {
                log.warn("User with userId {} not found", post.getUserId());
                // 根据业务需求决定如何处理，例如使用默认头像或跳过该帖子
                String defaultImg = "default_img_url"; // 默认头像 URL
                postWithCommentsList.add(new PostWithComments(post, null, defaultImg, null));
                continue;
            }


            String postimg = user.getImg();
            postWithCommentsList.add(new PostWithComments(post, null, postimg, null));
        }
        return Result.success(postWithCommentsList, "返回成功");

    }

    //查看帖子详情
    @PostMapping("/getpostbyid")
    public Result<PostWithComments> getpostbyid(Integer postId) {
        log.info(postId.toString());

        // 查询帖子
        LambdaQueryWrapper<Forumpost> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Forumpost::getPostId, postId);
        Forumpost post = forumpostService.getOne(queryWrapper);

        // 查询评论
        LambdaQueryWrapper<Postcomment> query1Wrapper = new LambdaQueryWrapper<>();
        query1Wrapper.eq(Postcomment::getPostId, postId);
        List<Postcomment> postcomments = postcommentService.list(query1Wrapper);

        // 根据帖子ID查询发帖人头像
        LambdaQueryWrapper<User> query2Wrapper = new LambdaQueryWrapper<>();
        query2Wrapper.eq(User::getUserId, post.getUserId());
        User user = userService.getOne(query2Wrapper);
        String postimg = user.getImg();

        // 根据评论ID查询评论人头像URL，并保持原有评论顺序
        List<String> commentImgUrls = new ArrayList<>();
        for (Postcomment comment : postcomments) {
            LambdaQueryWrapper<User> query3Wrapper = new LambdaQueryWrapper<>();
            query3Wrapper.eq(User::getUserId, comment.getUserId());
            User commentUser = userService.getOne(query3Wrapper);
            if (commentUser != null && commentUser.getImg() != null) {
                commentImgUrls.add(commentUser.getImg());
            } else {
                // 可选：添加默认头像URL或null，取决于业务逻辑要求
                commentImgUrls.add("default_avatar_url_or_null");
            }
        }


        PostWithComments postWithComments = new PostWithComments(post, postcomments, postimg, commentImgUrls);
        return Result.success(postWithComments, "返回成功");
    }



//    //根据帖子id查看帖子评论
//    @GetMapping("/getpostcommentbyid")
//    public Result<List<Postcomment>> getpostcommentbyid(Integer postId) {
//        log.info(postId.toString());
//
//        LambdaQueryWrapper<Postcomment> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(Postcomment::getPostId, postId);
//        List<Postcomment> postcomments = postcommentService.list(queryWrapper);
//
//        return Result.success(postcomments, "返回成功");
//    }

}
